# -*- coding: UTF-8 -*-
""" Shows the results of previous game

    From GameState It needs a pair of players and list of words they guessed.
    It also needs current_word if it was time-outed, or None
    It can change phase to the screen "from -> to"
    furthermore, here player can delete words, if pair failed it,
    but clicked, that they guessed it
"""

import os
from kivy.clock import Clock

from ui.fittable_widgets import FittableButton, FittableLabel
from kivy.properties import StringProperty
from kivy.properties import NumericProperty
from kivy.uix.popup import Popup
from model.gamestate import *
from model.gamestate import Phase
from ui.hat_widget import HatWidget, HatPopup
from kivy.clock import Clock
from ui.hat_widget import open_ok_popup
from kivy.uix.boxlayout import BoxLayout
from ui.scroll_popup import open_scroll_popup
from kivy.uix.image import Image
from kivy.uix.checkbox import CheckBox
from kivy.uix.togglebutton import ToggleButton
from kivy.app import App
from kivy.logger import Logger
from constants import COLOR

colors = {WordGuessResult.FAIL: 'red',
          WordGuessResult.GUESS: 'green',
          WordGuessResult.TIME_OUT: 'default',
          WordGuessResult.PUT_BACK: 'grey',
          WordGuessResult.NOT_GUESSED: 'default'}


class HelpButton(FittableButton):
    def __init__(self, text, root, **kwargs):
        self.root = root
        self.word_text = text
        super(HelpButton, self).__init__(**kwargs)

    def get_help(self):
        if self.word_text.lower() in self.root.presenter.\
           explanatory_dictionary.dictionary:
            open_scroll_popup(self.word_text.lower(),
                              self.root.presenter.explanatory_dictionary.
                              dictionary[self.word_text.lower()],
                              self.root)
        else:
            open_ok_popup(self.word_text, _('No information'), self.root)


class SendReportButton(FittableButton):

    def __init__(self, text, root, **kwargs):
        self.root = root
        self.word_text = text
        super(SendReportButton, self).__init__(**kwargs)

    def send_report(self):
        open_ok_popup(self.word_text, 'Coming later', self.root)


class AddToFavoriteButton(FittableButton):

    def __init__(self, text, root, **kwargs):
        self.root = root
        self.word_text = text
        super(AddToFavoriteButton, self).__init__(**kwargs)

    def add(self):
        open_ok_popup(self.word_text, 'Coming later', self.root)


class ResultLayout(BoxLayout):

    def on_checkbox_active(self, checkbox, value):
        if value:
            self.widget.guess_result.result = self.result
            self.widget.word_btn.color_name = colors[self.result]
            self.widget.root.update()
            self.parent.root.dismiss()
        else:
            self.check_box.active = True

    def on_label_release(self, strange_var):
        self.check_box.active = not self.check_box.active
        self.on_checkbox_active(self, self.check_box.active)

    def __init__(self, widget, result, text):
        self.widget = widget
        self.result = result

        super(ResultLayout, self).__init__(orientation='horizontal',
                                           size_hint=(1, 1))
        self.check_box = CheckBox(group='edit_wgr',
                                  size_hint=(0.1, 1))
        self.check_box.active = widget.guess_result.result == result
        self.check_box.bind(active=self.on_checkbox_active)

        self.label = FittableButton(text=text,
                                    color=COLOR[colors[self.result]],
                                    background_color=(1, 1, 1, 0),
                                    on_release=self.on_label_release)
        self.add_widget(self.check_box)
        self.add_widget(self.label)


class WordGuessResultLayout(BoxLayout):

    def __init__(self, root, *buttons):
        self.root = root
        super(WordGuessResultLayout, self).__init__(orientation='vertical',
                                                    size_hint=(1, 1))
        for button in buttons:
            self.add_widget(button)


class WGSPopup(HatPopup):

    def __init__(self, WGR, widget, **kwargs):
        self.widget = widget
        content = BoxLayout(orientation='vertical', size_hint=(1, 1))
        Otherbuttons = BoxLayout(orientation='vertical', size_hint=(1, 0.5))
        super(WGSPopup, self).__init__(content=content,
                                       title=WGR.word.text,
                                       size_hint=(None, None),
                                       size=(widget.root.width / 1.5,
                                             widget.root.height / 1.5))

        Otherbuttons.add_widget(HelpButton(widget.guess_result.word.text,
                                widget.root))
        Otherbuttons.add_widget(SendReportButton(widget.guess_result.word.text,
                                widget.root))
        Otherbuttons.add_widget(AddToFavoriteButton(widget.guess_result.
                                                    word.text, widget.root))

        if widget.guess_result.result == WordGuessResult.TIME_OUT:
            widget.guess_result.result = WordGuessResult.NOT_GUESSED

        WGRbuttons = WordGuessResultLayout(self,
                                           ResultLayout(widget,
                                                        WordGuessResult.GUESS,
                                                        _('Guessed')),
                                           ResultLayout(widget,
                                                        WordGuessResult.FAIL,
                                                        _('Fail')),
                                           ResultLayout(widget,
                                                        WordGuessResult.
                                                        NOT_GUESSED,
                                                        _('Not guessed')),
                                           )
        if widget.guess_result.result != WordGuessResult.PUT_BACK:
            content.add_widget(WGRbuttons)

        content.add_widget(Otherbuttons)
        self.open()


class WordLabel(BoxLayout):
    colors = {WordGuessResult.FAIL: 'red',
              WordGuessResult.GUESS: 'green',
              WordGuessResult.TIME_OUT: 'default',
              WordGuessResult.PUT_BACK: 'grey',
              WordGuessResult.NOT_GUESSED: 'default'}

    def __init__(self, guess_result, root, **kwargs):
        self.guess_result = guess_result
        self.word = guess_result
        self.root = root
        super(WordLabel, self).__init__(**kwargs)

    def swap_result(self):
        WGSPopup(self.guess_result, self)


class ResultsOfOnePair(HatWidget):
    next_phase = NumericProperty()
    words_left = NumericProperty()

    def __init__(self, gamestate, presenter, **kwargs):
        """ Sets up the screen.
        """
        self.button_text = {Phase.GAME_RESULTS: _('Game results'),
                            Phase.FROM_TO: _('Pass the hat')}
        self.next_phase = Phase.FROM_TO

        super(ResultsOfOnePair, self).__init__(presenter, **kwargs)

        self.gamestate = gamestate
        self.update_replay_button()

        self.gamestate.players.players_select_strategy.is_same_pair = False
        self.gamestate.game_round.is_replayed = False

        self.word_list.bind(minimum_height=self.word_list.setter('height'))

        for word in self.gamestate.game_round.words:
            box_layout = BoxLayout(orientation='horizontal',
                                   size_hint=(1, None), height='35sp')
            box_layout.add_widget(WordLabel(word, self))
            self.word_list.add_widget(box_layout)
        self.update()

    def to_next(self, is_finishing=False):
        """ changes phase to 'FROM_TO' or 'GAME_RESULTS'
        called on 'Next Round' button release
        """
        is_replayed = self.gamestate.game_round.is_replayed
        if not is_replayed:
            for guess in self.gamestate.game_round.words[:]:
                if guess.result in [WordGuessResult.NOT_GUESSED,
                                    WordGuessResult.TIME_OUT]:
                    self.gamestate.hat.add_word(guess.word)

        if self.gamestate.rounds is None:
            self.gamestate.rounds = []
        self.gamestate.rounds.append(self.gamestate.game_round)
        self.gamestate.game_round = None
        self.okbutton.enabled = False
        if is_finishing:
            self.presenter.change_phase(Phase.CURRES)
        else:
            self.presenter.change_phase(self.next_phase)

    def replay_round(self):
        self.gamestate.players.players_select_strategy.is_same_pair = True
        self.gamestate.game_round.is_replayed = True
        self.to_next()

    def update(self):
        self.update_replay_button()
        self.update_next_phase()

    def update_next_phase(self):
        self.next_phase = Phase.FROM_TO
        self.words_left = len(self.gamestate.hat.words)
        for guess in self.gamestate.game_round.words:
            if guess.result in [WordGuessResult.NOT_GUESSED,
                                WordGuessResult.TIME_OUT]:
                self.words_left += 1
        self.max_round_num = self.gamestate.settings.max_round_num
        self.circle_num = self.gamestate.circle_num
        if (self.words_left == 0) \
           or ((self.max_round_num is not None)
               and (self.circle_num > self.max_round_num)):
            self.next_phase = Phase.GAME_RESULTS
        else:
            self.next_phase = Phase.FROM_TO

    def update_replay_button(self):
        can_replay = self.presenter.settings.game.may_replay_round and \
            len(self.gamestate.hat.words) > 0
        self.end_button.enabled = can_replay
